package Model;

import exception.UserException;
import java.util.ArrayList;
import util.Encrypt;
import util.Fields;

public class User extends Base {
    public User(){
        this.Key = "id";
        this.Table = "user";
    }
    
    public long id;
    public String email;
    public String password;
    public int block;
    
    public boolean addNew() throws UserException   {
        this.checkPassword();
        this.password = Encrypt.SHA1(this.password);
        return this.Insert("email,password").Status;
    }
    
    public boolean block()  {
        this.block = 1;
        return this.Update("block").Status;
    }
    
    public boolean unblock()    {
        this.block = 0;
        return this.Update("block").Status;
    }
    
    public boolean remove() {
        return this.Delete().Status;
    }
    
    public boolean edit() throws UserException   {
        String editFields = "";
        if (this.password != null && !this.password.isEmpty())   {
            this.checkPassword();
            this.password = Encrypt.SHA1(this.password);
            editFields += ",password";
        }
        
        if (editFields.isEmpty())   {
            return true;
        }
        
        editFields = editFields.substring(1);
        return this.Update(editFields).Status;
    }
    
    public static User login(String email, String password)   {
        User user = new User();
        user.email = email;
        try {
            user.password = Encrypt.SHA1(password);
        } catch (Exception ex)   {
            throw new RuntimeException(ex.getMessage());
        }

        ArrayList list = user.find("username,password");
        if (list.isEmpty())
            return null;
        user.id = (Long) Fields.getField(list.get(0), "id");
        user.Instance();    
        return user;
    }
    
    public boolean emailExist()  {
        return this.isExist("email");
    }
    
    public void checkEmail() throws UserException  {
        
    }
    
    public void checkPassword() throws UserException {
        if (this.password == null || this.password.length() < 6 || this.password.length() > 32)
            throw new UserException("Password length must be between 6 and 32");
    }
}